package com.sline.ThreadCommunication;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

public class Demo3_ReentrantLock {
    public static void main(String[] args) {
        final Printer1 p1 = new Printer1();
        new Thread() {
            public void run() {
                while (true) {
                    try {
                        p1.print1();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }.start();
        new Thread() {
            public void run() {
                while (true) {
                    try {
                        p1.print2();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }.start();
        new Thread() {
            public void run() {
                while (true) {
                    try {
                        p1.print3();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }.start();
    }
}

class Printer2 {
    private int flag = 1;
    private ReentrantLock r = new ReentrantLock();
    private Condition c1 = r.newCondition();
    private Condition c2 = r.newCondition();
    private Condition c3 = r.newCondition();
    public void print1() throws InterruptedException {
        r.lock();
        if (flag != 1) {
            c1.await();
        }
        System.out.print("黑");
        System.out.print("马");
        System.out.print("程");
        System.out.print("序");
        System.out.print("员");
        System.out.println("");
        flag = 2;
        c2.signal();
        r.unlock();
    }
    public void print2() throws InterruptedException {

        r.lock();
        if (flag != 2) {
            c2.await();
        }
        System.out.print("传");
        System.out.print("智");
        System.out.print("播");
        System.out.print("客");
        System.out.println("");
        flag = 3;
        c3.signal();
        r.unlock();
    }

    public void print3() throws InterruptedException {

        r.lock();
        if (flag != 3) {
            c3.await();
        }

        System.out.print("A");
        System.out.print("B");
        System.out.print("C");
        System.out.print("D");
        System.out.print("E");
        System.out.print("F");
        System.out.print("G");
        System.out.println("");
        flag = 1;
        c1.signal();
        r.unlock();
    }
}
